<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" center class="borderRadius10" v-model="state.dialog.isShowDialog" width="490">
			<el-form ref="roleDialogFormRef" :rules="rules" :model="state.ruleForm" label-width="120px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="规格模板类型："  prop="typeId">
							<el-select v-model="state.ruleForm.typeId" placeholder="请选择模板类型" class="width260">
								<el-option v-for="item in state.productTypeList" :key="item.value"
									:label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="规格模板名称："  prop="name">
							<el-input class="width260" v-model="state.ruleForm.tplName" placeholder="请输入标题名称" clearable></el-input>
						</el-form-item>
					</el-col>
                    <el-col v-for="(item,index) in state.ruleForm.specList" :key="index" :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
						<el-form-item label="">
							<section>
								<el-tag class="mx-1" closable @close="handleClose(index)">{{ item.specName }}</el-tag>
								<div>
									<el-tag class="mr15" closable  v-for="(item1,index1) in item.specItemList" :key="index1" @close="handleItemClose(index,index1)">{{ item1.specItemName }}</el-tag>
								</div>
							</section>
						</el-form-item>
					</el-col>
					<el-col v-if="state.isAddSpecItem" class="mb20">
						<el-form ref="addSpecRef" :rules="rules" :model="state.addSpecForm" label-width="120px">
							<el-row>
								<el-col :span="24" class="flex">
									<el-form-item label="规格名称：" prop="specId">
										<el-select v-model="state.addSpecForm.specId" placeholder="请选择规格名称" class="width160">
											<el-option v-for="item in state.specList" 
												:disabled="state.ruleForm.specList.some((obj:any) => obj.specId == item.specId)"
												:key="item.specId" :label="item.specName" :value="item.specId" />
										</el-select>
									</el-form-item>
									<el-button class="ml20" type="primary" @click="addSpecItemFun(addSpecRef)">添加</el-button>
									<el-button type="primary" @click="isAddSpecItemFun(false)">取消</el-button>
								</el-col>
							</el-row>
						</el-form>
					</el-col>
					<el-col v-if="!state.isAddSpecItem" :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="">
							<el-button type="primary" @click="isAddSpecItemFun(true)">添加规格</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmitForm(roleDialogFormRef)">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">

import { reactive, ref } from 'vue';
import {  ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import { templateAdd, chainList, specificationList } from '/@/api/commodity';


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 定义变量内容
const addSpecRef = ref<FormInstance>();
// 定义变量内容
const roleDialogFormRef = ref();
const state = reactive({
	loading:false,
	productTypeList: [] as Array<any>, //模板类型
	specList: [] as Array<any>, //规格列表
	ruleForm: {
		tplId: null,
		typeId: null, //类型
		tplName: '', // 模板名称
		specList:[] as any,
	},
	addSpecForm:{
		specId: null, // 选中规格项ID
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	isAddSpecItem:false
});

const rules = reactive<FormRules<any>>({
	typeId: [ { required: true, message: '请选择模板类型', trigger: 'change' }],
	tplName: [ { required: true, message: '请输入规格名称', trigger: 'blur' }],
	specId: [ { required: true, message: '请选择模板规格项', trigger: 'change', }],
})


// 打开弹窗
const openDialog = (type: string, row?: RowRoleType) => {
	getChainList();
	getSpecificationList();
	state.dialog.type = type
	if (type === 'edit') {
		state.dialog.title = '模板编辑';
		state.dialog.submitTxt = '修 改';
		state.ruleForm.tplId = row.tplId;
		state.ruleForm.typeId = row.typeId;
		state.ruleForm.tplName = row.tplName;
		state.ruleForm.specList = row.specList;
	} else {
		state.dialog.title = '模板新增';
		state.dialog.submitTxt = '新 增';
		state.ruleForm =  {
			tplId: null,
			typeId: null, //类型
			tplName: '', // 模板名称
			specList:[] as any,
		};
	}
	state.dialog.isShowDialog = true;
};

// 模板类型(跟随商品选择)
const getChainList = async () => {
	const { results } = await chainList({ mode: null});
	state.productTypeList = results.children
}

// 规格列表
const getSpecificationList = async () => {
	let params = {
		pageNum: 1,
		pageSize: 100,
	}
	const { results } = await specificationList(params);
	state.specList = results.records
}


// 添加规格项
const addSpecItemFun =  (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 当前选中的规格数据
			let data = state.specList.find(item => item.specId === state.addSpecForm.specId);
			let param = {
				specId:data.specId,
				specName:data.specName,
				specItemList:[] as any
			}
			data.specItemList.map((item:any) =>{
				param.specItemList.push({
					specItemId: item.specItemId,
					specItemName: item.specItemName,
				})
			})
			state.ruleForm.specList.push(param);
			state.addSpecForm.specId = null;
			state.isAddSpecItem = false;
		} else {
			return false;
		}
	});
};

// 移除规格项
const handleClose = (index: number) => {
	state.ruleForm.specList.splice(index,1)
}
 
// 移除规格值
const handleItemClose = (index: number,index1: number) => {
	state.ruleForm.specList[index].specItemList.splice(index1,1)
	if(state.ruleForm.specList[index].specItemList.length == 0){
		state.ruleForm.specList.splice(index,1)
	}
}

// 添加规格项展示关闭
const isAddSpecItemFun = (a: any) => {
	state.isAddSpecItem = a
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};


// 添加规格项
const onSubmitForm =  (formEl: FormInstance | undefined)  => {
	if (!formEl) return;
	formEl.validate ( async (valid: boolean)  => {
		if (valid) {
			if(state.ruleForm.specList.length == 0){
				ElMessage.success('请至少添加一项商品规格');
				return false
			}else{
				let params = {
					tplId: state.ruleForm.tplId,
					typeId: state.ruleForm.typeId,
					tplName: state.ruleForm.tplName,
					specList: state.ruleForm.specList,
				}
				const { results } = await templateAdd(params);
				ElMessage.success('提交成功');
				state.loading = false;
				closeDialog();
				emit('refresh');
			}
		} else {
			return false;
		}
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">

</style>
